<?php
namespace V1\Controller;
/**
 * 常用操作控制类
 *
 * 短信相关：发送
 *     
 * @author wangzhenxian
 * @package application.components 
 */
use Think\Controller;
use Think\Cache;
include_once 'redis.php';
class Util1Controller extends BaseController {
    
     protected $errorCode = array(
        'sendsms' => array(
            '-1' => '短信发送频度在120秒',
            '-2' => '短信写入数据库' ,
            '-3' => '短信发送不成功' ,
        ),
    );
    public function redisset()
    {
        echo 'set redis<br/>';
//        
//        $Cache = Cache::getInstance('',array('expire'=>'60'));
//        $Cache->set('name','ThinkPHP');  // 缓存name数据
//        $value = $Cache->get('name');  // 获取缓存的name数据
//        echo $value;
//        $Cache->rm('name');  // 删除缓存的name数据
        
//         S('aaa','Think',array('expire'=>20,'prefix'=>'game'));
//        
//         $collect = new \Api\Controller\CollectController();
//         $collect->rtstock('2015-04-22','sh601857');
         
         
         
//         $redis = new \Redis();
//         $redis->connect('127.0.0.1', 6379);
////        
//         if(!$redis->exists('industryInfoHashMap')){
//           $result = M('IndustryInfo',C('RealTimeStockDb')['DB_PREFIX'],
//                     C('RealTimeStockDb')['DB_CONN'])->where("state=1")->field(['industrycode,industry'])->select();
//           foreach ($result as $industryInfo) {
////                $redis->sAdd('industryInfoList',$industryInfo['industrycode']); //List
//               $redis->hSet('industryInfoHashMap',$industryInfo['industrycode'],$industryInfo['industry']);
//            }
//         }
//         $industryInfoList = $redis->sMembers('industryInfoList');
         
//         $industryCodeList = $redis->hKeys('industryInfoHashMap');
//         
//         foreach ($industryCodeList as $industryCode) {
//             if(!$redis->exists("industryStockList{$industryCode}")){
//                $result = M('IndustryStock',C('RealTimeStockDb')['DB_PREFIX'],
//                           C('RealTimeStockDb')['DB_CONN'])->where("state=1 AND industrycode='{$industryCode}'")->field('stockcode')->select();
//                foreach ($result as $value) {
//                    $stockcode=getStockWithFlag($value['stockcode']);
//                    $redis->sAdd("industryStockList{$industryCode}",$stockcode);   
//                }               
//             }
//         }
//         
//         //获取每个行业涨跌幅最高的股票信息汇总
////       $sortedTopIndustryStockByPercent= $redis->zrevrange();
//         
//         if(!$redis->exists('sortedTopIndustryStockByPercent')){
//             
//            foreach ($industryCodeList as $industryCode) {
//
//                $industryStockList = $redis->sMembers("industryStockList{$industryCode}");
//
//                $where = array('stock_code'=>array('in',$industryStockList));
//
//                $result = M('Stock20150702',C('RealTimeStockDb')['DB_PREFIX'],
//                              C('RealTimeStockDb')['DB_CONN'])->where($where)->order('percent desc,id desc')->find();
//
//
//                if(!empty($result)){
//                     $result['industryCode']=$industryCode;
//                     $result['industry']= $redis->hget('industryInfoHashMap',$industryCode);
//                     $redis->zAdd('sortedTopIndustryStockByPercent',$result['percent'], json_encode($result));
//                }
//            }
//            $redis->expire('sortedTopIndustryStockByPercent',3000);//缓存5分钟
//            
//         }
                    
    }
        public function redisget()
    {
        echo 'get redis<br/>';
        
        echo  S('aaa','',array('prefix'=>'game'));
        
//        $stockInfo = S('sh601857','',array('prefix'=>'game'));
//        
//        print_r($stockInfo);
                    
    }
    public function index(){
        $json='{
    "error_code": 0,
    "reason": "success",
    "result": {
        "data": [{
            "total": 153
        },
        {
            "exchangeCD": "XSHE",
            "calendarDate": "2014-08-21",
            "isOpen": 1,
            "prevTradeDate": "2014-08-20",
            "isWeekEnd": 0,
            "isMonthEnd": 0,
            "isQuarterEnd": 0,
            "isYearEnd": 0
        },
        {
            "exchangeCD": "XSHE",
            "calendarDate": "2014-08-22",
            "isOpen": 1,
            "prevTradeDate": "2014-08-21",
            "isWeekEnd": 1,
            "isMonthEnd": 0,
            "isQuarterEnd": 0,
            "isYearEnd": 0
        },
        {
            "exchangeCD": "XSHE",
            "calendarDate": "2014-08-23",
            "isOpen": 0,
            "prevTradeDate": "2014-08-22",
            "isWeekEnd": 0,
            "isMonthEnd": 0,
            "isQuarterEnd": 0,
            "isYearEnd": 0
        },
        {
            "exchangeCD": "XSHE",
            "calendarDate": "2014-08-24",
            "isOpen": 0,
            "prevTradeDate": "2014-08-22",
            "isWeekEnd": 0,
            "isMonthEnd": 0,
            "isQuarterEnd": 0,
            "isYearEnd": 0
        },
        {
            "exchangeCD": "XSHE",
            "calendarDate": "2014-08-25",
            "isOpen": 1,
            "prevTradeDate": "2014-08-22",
            "isWeekEnd": 0,
            "isMonthEnd": 0,
            "isQuarterEnd": 0,
            "isYearEnd": 0
        },
        {
            "exchangeCD": "XSHE",
            "calendarDate": "2014-08-26",
            "isOpen": 1,
            "prevTradeDate": "2014-08-25",
            "isWeekEnd": 0,
            "isMonthEnd": 0,
            "isQuarterEnd": 0,
            "isYearEnd": 0
        },
        {
            "exchangeCD": "XSHE",
            "calendarDate": "2014-08-27",
            "isOpen": 1,
            "prevTradeDate": "2014-08-26",
            "isWeekEnd": 0,
            "isMonthEnd": 0,
            "isQuarterEnd": 0,
            "isYearEnd": 0
        },
        {
            "exchangeCD": "XSHE",
            "calendarDate": "2014-08-28",
            "isOpen": 1,
            "prevTradeDate": "2014-08-27",
            "isWeekEnd": 0,
            "isMonthEnd": 0,
            "isQuarterEnd": 0,
            "isYearEnd": 0
        },
        {
            "exchangeCD": "XSHE",
            "calendarDate": "2014-08-29",
            "isOpen": 1,
            "prevTradeDate": "2014-08-28",
            "isWeekEnd": 1,
            "isMonthEnd": 1,
            "isQuarterEnd": 0,
            "isYearEnd": 0
        },
        {
            "exchangeCD": "XSHE",
            "calendarDate": "2014-08-30",
            "isOpen": 0,
            "prevTradeDate": "2014-08-29",
            "isWeekEnd": 0,
            "isMonthEnd": 0,
            "isQuarterEnd": 0,
            "isYearEnd": 0
        },
        {
            "exchangeCD": "XSHE",
            "calendarDate": "2014-08-31",
            "isOpen": 0,
            "prevTradeDate": "2014-08-29",
            "isWeekEnd": 0,
            "isMonthEnd": 0,
            "isQuarterEnd": 0,
            "isYearEnd": 0
        },
        {
            "exchangeCD": "XSHE",
            "calendarDate": "2014-09-01",
            "isOpen": 1,
            "prevTradeDate": "2014-08-29",
            "isWeekEnd": 0,
            "isMonthEnd": 0,
            "isQuarterEnd": 0,
            "isYearEnd": 0
        },
        {
            "exchangeCD": "XSHE",
            "calendarDate": "2014-09-02",
            "isOpen": 1,
            "prevTradeDate": "2014-09-01",
            "isWeekEnd": 0,
            "isMonthEnd": 0,
            "isQuarterEnd": 0,
            "isYearEnd": 0
        },
        {
            "exchangeCD": "XSHE",
            "calendarDate": "2014-09-03",
            "isOpen": 1,
            "prevTradeDate": "2014-09-02",
            "isWeekEnd": 0,
            "isMonthEnd": 0,
            "isQuarterEnd": 0,
            "isYearEnd": 0
        },
        {
            "exchangeCD": "XSHE",
            "calendarDate": "2014-09-04",
            "isOpen": 1,
            "prevTradeDate": "2014-09-03",
            "isWeekEnd": 0,
            "isMonthEnd": 0,
            "isQuarterEnd": 0,
            "isYearEnd": 0
        },
        {
            "exchangeCD": "XSHE",
            "calendarDate": "2014-09-05",
            "isOpen": 1,
            "prevTradeDate": "2014-09-04",
            "isWeekEnd": 1,
            "isMonthEnd": 0,
            "isQuarterEnd": 0,
            "isYearEnd": 0
        },
        {
            "exchangeCD": "XSHE",
            "calendarDate": "2014-09-06",
            "isOpen": 0,
            "prevTradeDate": "2014-09-05",
            "isWeekEnd": 0,
            "isMonthEnd": 0,
            "isQuarterEnd": 0,
            "isYearEnd": 0
        },
        {
            "exchangeCD": "XSHE",
            "calendarDate": "2014-09-07",
            "isOpen": 0,
            "prevTradeDate": "2014-09-05",
            "isWeekEnd": 0,
            "isMonthEnd": 0,
            "isQuarterEnd": 0,
            "isYearEnd": 0
        },
        {
            "exchangeCD": "XSHE",
            "calendarDate": "2014-09-08",
            "isOpen": 0,
            "prevTradeDate": "2014-09-05",
            "isWeekEnd": 0,
            "isMonthEnd": 0,
            "isQuarterEnd": 0,
            "isYearEnd": 0
        },
        {
            "exchangeCD": "XSHE",
            "calendarDate": "2014-09-09",
            "isOpen": 1,
            "prevTradeDate": "2014-09-05",
            "isWeekEnd": 0,
            "isMonthEnd": 0,
            "isQuarterEnd": 0,
            "isYearEnd": 0
        }]
    }
}';
        $result = json_decode($json);
        $calendar = M('CommonCalendar');
         $array = $result->result->data;
         foreach ($array as $key => $value) {
            
             if($key==0) continue;
             
             $data=array(
                 'exchangeCD'=>$value->exchangeCD,
                 'calendarDate'=>$value->calendarDate,
                 'isOpen'=>$value->isOpen,
                 'prevTradeDate'=>$value->prevTradeDate,
                 'isWeekEnd'=>$value->isWeekEnd,
                 'isMonthEnd'=>$value->isMonthEnd,
                 'isQuarterEnd'=>$value->isQuarterEnd,
                 'isYearEnd'=>$value->isYearEnd,
             );
            if($calendar->create($data)){
                   $uid = $calendar->add();
                   if(!$uid){
                       echo -1;
                   }
                  
            } 
         }
    }
    public function aa(){
       //$url = "http://xueqiu.com/stock/quote_order.json?page=1&size=400&order=desc&exchange=CN&stockType=cyb&column=symbol%2Cname%2Ccurrent%2Cchg%2Cpercent%2Clast_close%2Copen%2Chigh%2Clow%2Cvolume%2Camount%2Cmarket_capital%2Cpe_ttm%2Chigh52w%2Clow52w%2Chasexist&orderBy=symbol&_=1431221415387";
       //$url ='http://xueqiu.com/stock/cata/stocklist.json?page=1&size=90&order=desc&orderby=percent&type=11%2C12&_=1431224936246';
       $url ='http://xueqiu.com/stock/quote_order.json?page=1&size=10000&order=desc&exchange=CN&stockType=sha&column=symbol%2Cname%2Ccurrent%2Cchg%2Cpercent%2Clast_close%2Copen%2Chigh%2Clow%2Cvolume%2Camount%2Cmarket_capital%2Cpe_ttm%2Chigh52w%2Clow52w%2Chasexist&orderBy=percent&_=1431225313748';
        $conf = array(
           'cookie'=>'__utma=1.1623961383.1430982406.1431075580.1431081065.6; __utmz=1.1430982406.1.1.utmcsr=segmentfault.com|utmccn=(referral)|utmcmd=referral|utmcct=/q/1010000001837990/a-1020000002411728; Hm_lvt_1db88642e346389874251b5a1eded6e3=1430982406,1430982675,1431053979; xq_a_token=39d6304bf28af3d0e6424795e0d0b210c91568c6; xq_r_token=365b51d13be704cbff32038faffa8dfef2a1914c; __utmc=1; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1431221415',
       );
       $out = \Org\Net\Http::fsockopenDownload($url,$conf);
       $result = json_decode($out);
    
       $model = M('StockBase');
       foreach ($result->data as $value) {
         $info = array(
                   'stock_code' => $value[0],
                   'stock_name' => $value[1],
                   'exchangecd' =>'',
             'stock_keywords' => '','stock_logo' => '','create_time' => time(),'update_time' => time(),
             'status'=>0,
           );
           if($model->create($info)){
                  $model->add();
           } else {
                  echo $model->getError(); 
                  break;
           } 
         
       }
         
    }
    public function sendSms(){
       
       if(!IS_POST){
             throw new \Api\Library\Exception\BadRequest("该方法只支持POST请求", 1);
       }
       $data = array("code" => 0,"msg" => "","info"=>array());
       
       $phonenumber = I('post.n','','/^\d{11}$/');

       if(empty($phonenumber)){
            throw new \Api\Library\Exception\BadRequest("参数异常", 1);
       }
       
       $smsModel = D('Sms');
       //是否已经在可重复发送短信的时间内发送过短信
       if($smsModel->checkRepeatSms($phonenumber)){
           $data['code'] = -1;
           $data['msg'] = self::$errorCode[strtolower(ACTION_NAME)]['-1'];
       }else{
        //生成短信验证码
        //$code = mt_rand(1000, 9999);
        $code=2468; //便于测试后期修改
        $sms_content_template = "您的验证码为：%s，请在10分钟内完成校验，如非本人操作，请忽略本短信。【涨跌福】";
        $sms_content =  sprintf($sms_content_template, $code);
        //写短信表
        $result = $smsModel->addSms($phonenumber,$code,$sms_content);

        if($result){
           //发送短信调用第三方短信接口
           //$error_code = sms($phonenumber,$sms_content);
           $error_code='1223333';//便于测试后期修改
           if(strlen($error_code)>3){
           //更新短信表中短信发送状态
           $smsModel->updateStatus($result,1);
           $data['info']['msg'] ='已发送短信至'.substr_replace($phonenumber, '****', 3,4);
           }else{
               $data['code'] = -3;
               $smsModel->updateStatus($result,$error_code);
               $data['msg'] = self::$errorCode[strtolower(ACTION_NAME)]['-3'];
           }
        }else {
            $data['code'] = -2;
            $data['msg'] = self::$errorCode[strtolower(ACTION_NAME)]['-2'];
        }
       }
      $this->responseResult($data);
    }
}